package cn.gdchent.springbootsecurity.utils;

import okhttp3.*;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传
 * http://www.360doc.com/content/18/0409/18/8335678_744234144.shtml
 */
public class OkHttpUploadUtils {

    // 使用OkHttp上传文件
    public static void uploadFile(File file) {
        OkHttpClient client = new OkHttpClient();
        MediaType contentType = MediaType.parse("application/octet-stream"); // 上传文件的Content-Type
        RequestBody fileBody = RequestBody.Companion.create(contentType, file); // 上传文件的请求体
        RequestBody requestBody=new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file","test.txt",fileBody)
                .build();
        Request request = new Request.Builder()
                .url("http://192.168.120.58:8086/uploadFile") // 上传地址
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 文件上传成功
                if (response.isSuccessful()) {
                    System.out.println("onResponse: " + response.body().string());
                } else {
                    System.out.println("onResponse: " + response.message());
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                // 文件上传失败
                System.out.println("onFailure: " + e.getMessage());
            }
        });
    }
}
